﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using LinkCard.Model;

namespace LinkCard.CustomerView.CusCp
{
    public partial class buy_glp : System.Web.UI.Page
    {
        public int configVersion = 0;
        public Int64 customerID = 0;
        public decimal PointToMile = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["USER"] == null) { Response.Redirect("login.aspx"); }
            if (Session["USERID"] == null) { Response.Redirect("login.aspx"); }

            customerID = Convert.ToInt64(Session["USERID"].ToString());

            LoadConfig();
        }
        private void LoadConfig()
        {
            var db = new TopLinkEntities();
            
            //Load config
            var configDb = db.Config.OrderByDescending(t => t.Version).First();

            this.mileConfig.InnerText = Utils.Utility.sDecimal(Convert.ToDecimal(configDb.PointToMile)) + " điểm / dặm";
            PointToMile = Convert.ToDecimal(configDb.PointToMile);
            this.configVersion = configDb.Version;

            //Load user point
            //Session["USERID"]
            var customerDb = db.Customers.Where(t => t.CustomerID == customerID).FirstOrDefault();

            this.currentPoint.InnerText = Utils.Utility.sDecimal(Convert.ToDecimal(customerDb.Point));

            //mile can exchange
            Int64 mileCanEx = Convert.ToInt64(customerDb.Point / configDb.PointToMile);
            //quy đổi dặm ra bội số của 1000
            Int64 mileRate = mileCanEx / 1000;
            mileCanEx = mileRate * 1000;
            this.mileCanExchange.InnerText = Utils.Utility.sDecimal(Convert.ToDecimal(mileCanEx));
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                var db = new TopLinkEntities();

                //Lưu trạng thái dặm
                var buyMile = new BuyMilesLog();

                buyMile.ConfigVersion = this.configVersion;
                buyMile.CustomerID = Convert.ToInt64(Session["USERID"].ToString());
                buyMile.DateLog = DateTime.Now;
                buyMile.MileToBuy = Convert.ToInt64(this.mileBuy.Value);
                buyMile.Status = 0;

                db.AddToBuyMilesLog(buyMile);
                
                //Trừ điểm của khách hàng
                var customer = db.Customers.Where(t => t.CustomerID == customerID).FirstOrDefault();
                customer.Point -= Convert.ToInt32(buyMile.MileToBuy*PointToMile);
                db.SaveChanges();

                Response.Redirect("message_box.aspx?msg=3", false);
            }
            catch
            {
                Response.Redirect("message_box.aspx?msg=0", false);
            }
        }
    }
}